package com.apes.scm.sal.saleOrder;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.framework.util.LogicalUtil;
import com.apes.scm.account.account.model.Cooperation;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.stock.model.Location;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 功能：分销订单
 *
 * @author xul
 * @create 2018-01-25 19:36
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SaleOrder.CONST_TABLE_NAME)
public class SaleOrder extends Model {
    public static final String CONST_TABLE_NAME = "sale_order";

    @Id
    @Column(name = "id")
    @Comment("分销订单号")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "分销订单", prefix = "FX%(company)%(yy)%(month)", padding = 5, useDateRange = true)
    private String id;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private PartyRole company;

    @Comment("部门")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    private Dept dept;

    @Comment("业务员")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "clerk_id", referencedColumnName = "id")
    private PartyRole clerk;

    @Comment("合同号")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "contract_id", referencedColumnName = "id")
    private Contract contract;

    @Comment("客户")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id", referencedColumnName = "id", nullable = false)
    private PartyRole customer;

    @Comment("源单据")
    @Column(name = "origin", length = 30)
    private String origin;

    @Column(name = "origin_business_type", length = 32)
    @Comment("源单据类型")
    private String originBusinessType;

    @Comment("来源单据")
    @Column(name = "source", length = 30)
    private String source;

    @Column(name = "source_business_type", length = 32)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @Comment("订单备注")
    @Column(name = "remark", length = 120)
    private String remark;

    @Comment("单据类型")
    @Column(name = "orderType", length = 60)
    private String orderType;  // FN_SALE 赋能销售，BZ_SALE 标准销售， RETAIL_SALE 零售， INNER_SALE 内协销售

    @Comment("合作方式")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cooperation_id", referencedColumnName = "id", nullable = false)
    private Cooperation cooperation;

    @Comment("审批日期")
    @Column(name = "date_approve")
    private Date dateApprove;

    @Comment("完成日期")
    @Column(name = "date_done")
    private Date dateDone;

    @Comment("计划日期")
    @Column(name = "date_planned")
    private Date datePlanned;

    @Comment("取消日期")
    @Column(name = "date_cancel")
    private Date dateCancel;

    @States(name = "订单状态", values = {
            @State(id = "sent", name = "创建"),
            @State(id = "confirmed", name = "审核"),
            @State(id = "done", name = "已完成"),
            @State(id = "vouched", name = "凭证完成"),
            @State(id = "cancel", name = "已取消")})
    @Column(name = "state", length = 10, nullable = false)
    private String state = "sent";

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "move_type", referencedColumnName = "id")
    private Enumeration moveType; //交货方式：("direct", "部分交货"), ("one", "一次性交货");

    @Comment("送货状态")
    @Column(name = "is_shipped", nullable = false)
    private boolean shipped = false;

    @Comment("开票状态")
    @Column(name = "invoice_status", nullable = false, length = 10)
    private String invoiceStatus = "no"; //账单状态: ("no", "未开票") (默认值), ("to_invoice", "开票中"), ("invoiced", "已开票")

    @Comment("税金")
    @Column(name = "amt_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double amtTax = 0;

    @Comment("不含税金额")
    @Column(name = "amt_untaxed", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double amtUntaxed = 0;

    @Comment("总计")
    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double amtTotal = 0; //总计

    @Column(name = "discount", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("折扣（返利）金额")
    private double discount = 0;


    @Comment("实收金额")
    @Column(name = "actual_total", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double actualAmount = 0;  //实收金额

    @Comment("已开票金额")
    @Column(name = "invoiced_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double invoicedAmount = 0;  //已开票金额

    @Transient
    private double unInvoicedAmount = 0;  //未开票金额


    public double getUnInvoicedAmount() {
        return Arith.sub(Arith.sub(amtTotal, discount), saleItems.stream().map(SaleOrderItem::getInvoicedAmount).reduce(Arith::add).orElse(0.0));
    }

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id")
    @Comment("库存位置")
    private Location location;

    @Comment("会员扩展信息编码")
    @Column(name = "customer_expand_id", length = 32)
    private String FnCustomerExpandId;

    public void setCommissionFlag(String commissionFlag) {
        if ("1".equals(commissionFlag))commissionFlag = "true";
        this.commissionFlag = commissionFlag;
    }

    @Comment("佣金对账单标记")
    @Column(name = "commission_flag", length = 32)
    private String commissionFlag;

    @Column(name = "unique_value")
    @Comment("唯一值")
    private String uniqueValue;

    @OneToMany(mappedBy = "saleOrder", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<SaleOrderItem> saleItems = new HashSet();

    public Set<SaleOrderItem> getSaleItems() {
        for (SaleOrderItem item : saleItems) {
            // 筛选数量为零的行
            if (item.getProductUomQty() == 0) {
                saleItems.remove(item);
                continue;
            }
            // 设置主表以及主表公司
            item.setSaleOrder(this);
            item.setCompany(this.company);
        }
        return saleItems;
    }

    /**
     * 功能: 判断当前单据是否需要收货
     */
    @Transient
    @States(name = "需要发货", values = {
            @State(id = "yes", name = "需发货"),
            @State(id = "no", name = "无需发货")})
    private String needShip;

    public String getNeedShip() {
        Set<SaleOrderItem> saleOrderItems = this.saleItems.stream()
                .filter(saleOrderItem -> saleOrderItem.getProductRule() == 0)
                .collect(Collectors.toSet());
        return saleOrderItems.isEmpty() ? "no" : "yes";
    }


    @Transient
    private Map<String, Double> curAmount;  // 获取可用额度与可用返利

    public Map<String, Double> getCurAmount() {
        if (state == null || id == null) return null;
        if (company == null || dept == null || customer == null) return null;
        SaleOrderService saleOrderService = SpringManager.getBean(SaleOrderService.class);
        return saleOrderService.getCurAmount(company, customer);
    }

    public void computeAmt() {
        // 赋予初始值
        amtUntaxed = 0;
        amtTax = 0;
        discount = 0;
        for (SaleOrderItem item : saleItems) {
            item.computeAmt();
            amtUntaxed += item.getPriceSubtotal();
            amtTax += item.getPriceTax();
            discount += item.getDiscount();
        }
        amtTotal = amtUntaxed + amtTax;
        actualAmount = amtTotal + discount;
    }


    /**
     * 功能：设置订单交货状态
     */
    public void setShipped() {
        long result = getSaleItems().stream()
                .filter(item ->
                        item.getProductUomQty() - item.getQtyCancle() != item.getQtyDeliver()
                                && item.getProductRule() == 0
                                && LogicalUtil.notIn(item.getProduct().getType(), "aut")
                ).count();
        if (result == 0) {
            setShipped(true);
            setState();
        }
    }

    /**
     * 功能：设置订单状态
     */
    public void setState() {
        if (!state.equals("confirmed")) return;
        if (shipped) {
            setDateDone(new Date());
            setState("done");
        }
    }


    public void judgeUnitPrice() {
        saleItems.forEach(
                item -> {
                    if (item.getPriceUnit() <= 0) {
                        throw new RuntimeException("分销单明细的单价不能为零！！！");
                    }
                });
    }
}
